package com.burgeon.backend.SHOPBACKEND.service.Impl;

import com.alibaba.fastjson.JSONObject;
import com.burgeon.backend.SHOP.service.SystemService;
import com.burgeon.backend.SHOPBACKEND.entity.weixin.WeiXinCode;
import com.burgeon.backend.SHOPBACKEND.mappers.WeiXinCodeMapper;
import com.burgeon.backend.SHOPBACKEND.service.WeCodeService;
import com.burgeon.backend.Util.menu.WeChatInfo;
import com.burgeon.backend.Util.menu.WeixinUtil;
import com.burgeon.backend.WeChat.GetAccesToken;
import com.burgeon.backend.service.WechatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

//import com.example.demo1.WeiTest1.util;
//import com.example.demo1.config.WechatQRCodeConfig;

@Service
public class WeCodeServiceImpl implements WeCodeService {
    // 获取ticket
    private static final String GET_QRCODE_URL = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token={TOKEN}";
    // 换取二维码
    private static final String QR_CODE_URL = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket={TICKET}";

    @Autowired
    private WeiXinCodeMapper weiXinCodeMapper;

    @Autowired
    private WechatService wechatService;



    public String getYJQrCode(String daoId) throws ParseException {
        String returnUrl = null;

        //A.1先从数据库查是否有二维码连接
        WeiXinCode weiXinCode = weiXinCodeMapper.getCodeBydaoId(daoId);
        Date d = new Date();
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
        String newDate = sf.format(d);
        Date newDe = sf.parse(newDate);
        //A.2如果有并且没过期
        if(null != weiXinCode && sf.parse(weiXinCode.getInvalidData()).after(newDe)){

            return weiXinCode.getCode();
        }

        //a.获取临时带参二维码
        //获取access_token
        //String access_token = WeGetAccessToken.getAccessToken();
        // String access_token = WeixinUtil.getAccessToken(WeChatInfo.WX_APPID,WeChatInfo.WX_APPSECRET).getToken();
        // String access_token = getAccesToken.GetAccesToken(WeChatInfo.token);
        //String access_token = systemService.GetAccesToken(WeChatInfo.token);
        String accessToken = wechatService.GetAccesToken(WeChatInfo.token);

        String req = "{\"expire_seconds\": 604800, \"action_name\": \"QR_STR_SCENE\", \"action_info\": {\"scene\": {\"scene_str\": "+daoId+" }}}";

        String url = GET_QRCODE_URL.replace("{TOKEN}", accessToken);
        //String p = req.toString();
        // JSONObject res= HttpClientUtil.doPost(req,url);
        //JSONObject res = SendRequest.sendPost(url,req);
        JSONObject res =WeixinUtil.httpRequest(url,"GET",req);
        //System.err.println("二维码"+res);

       // System.out.println("获取二维码出参" + res);
        String ticket = res.getString("ticket");
        returnUrl = QR_CODE_URL.replace("{TICKET}", ticket);
        System.err.println(returnUrl);

        //b.将临时带参二维码存入数据库
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, 30);
        Date date = cal.getTime();
        String invalidDate = sf.format(date);

        weiXinCodeMapper.InsertWXCode(daoId,returnUrl,invalidDate);

        return returnUrl;
    }




//    /**
//     * 获取微信公众号二维码
//     * @param codeType 二维码类型 "1": 临时二维码  "2": 永久二维码
//     * @param sceneId 场景值ID
//     * @param fileName 图片名称
//     */
////    public static void getWXPublicQRCode(String codeType, Integer sceneId, String fileName) {
////       // String wxAccessToken = getWXAccessToken();
////        String wxAccessToken = WeGetAccessToken.getAccessToken();
////        Map<String, Object> map = new HashMap<>();
////        if ("1".equals(codeType)) { // 临时二维码
////            map.put("expire_seconds", 604800);
////            map.put("action_name", "QR_SCENE");
////            Map<String, Object> sceneMap = new HashMap<>();
////            Map<String, Object> sceneIdMap = new HashMap<>();
////            sceneIdMap.put("scene_id", sceneId);
////            sceneMap.put("scene", sceneIdMap);
////            map.put("action_info", sceneMap);
////        } else if ("2".equals(codeType)) { // 永久二维码
////            map.put("action_name", "QR_LIMIT_SCENE");
////            Map<String, Object> sceneMap = new HashMap<>();
////            Map<String, Object> sceneIdMap = new HashMap<>();
////            sceneIdMap.put("scene_id", sceneId);
////            sceneMap.put("scene", sceneIdMap);
////            map.put("action_info", sceneMap);
////        }
////        String data = JSON.toJSONString(map);
////        // 得到ticket票据,用于换取二维码图片
////        JSONObject jsonObject = HttpUtils.httpsRequest("https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" + wxAccessToken, "POST", data);
////        String ticket = (String) jsonObject.get("ticket");
////        // WXConstants.QRCODE_SAVE_URL: 填写存放图片的路径
////        HttpUtils.httpsRequestPicture("https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" + URLEncoder.encode(ticket),
////                "GET", null, WXConstants.QRCODE_SAVE_URL, fileName, "png");
////    }















//    /**
//     * 获取二维码ticket后，通过ticket换取二维码图片展示
//     *
//     * @param accessToken
//     * @param ticket
//     * @param isShortUrl  是否需要展示
//     * @return
//     */
//    @Override
//    public String showQrCode(String accessToken, String ticket, boolean isShortUrl) {
//        String url = String.format(WechatQRCodeConfig.getShowQrcodeUrl(), EncodeUtils.urlEncode(ticket));
//        if (isShortUrl) {
//            return toShortQRCodeurl(accessToken, url);
//        }
//        return url;
//    }
//
//
//    /**
//     * 创建临时带参数二维码
//     *
//     * @param accessToken
//     * @param sceneId     场景Id
//     * @return
//     * @expireSeconds 该二维码有效时间，以秒为单位。 最大不超过2592000（即30天），此字段如果不填，则默认有效期为30秒。
//     */
//    @Override
//    public String createTempTicket(String accessToken, int sceneId, int expireSeconds) {
//        TreeMap<String, String> params = new TreeMap<>();
//        params.put("access_token", accessToken);
//        // output data
//        JsonObject data = new JsonObject();
//        data.addProperty("action_name", QRCodeConstant.QR_SCENE);
//        data.addProperty("expire_seconds", expireSeconds);
//        JsonObject scene = new JsonObject();
//        scene.addProperty("scene_id", sceneId);
//        JsonObject actionInfo = new JsonObject();
//        actionInfo.add("scene", scene);
//        data.add("action_info", actionInfo);
//        String result = HttpUtil.doPost(WechatQRCodeConfig.getCreateTicketUrl(), params, data.toString());
//        WechatQRCode qrcode = JsonUtil.fromJson(result, WechatQRCode.class);
//        return qrcode == null ? null : qrcode.getTicket();
//    }
//
//    /**
//     * 创建临时带参数二维码(字符串)
//     *
//     * @param accessToken
//     * @param sceneStr    场景Id
//     * @return
//     * @expireSeconds 该二维码有效时间，以秒为单位。 最大不超过2592000（即30天），此字段如果不填，则默认有效期为30秒。
//     */
//    @Override
//    public String createTempTicket(String accessToken, String sceneStr, int expireSeconds) {
//        TreeMap<String, String> params = new TreeMap<>();
//        params.put("access_token", accessToken);
//        // output data
//        JsonObject data = new JsonObject();
//        data.addProperty("action_name", QRCodeConstant.QR_STR_SCENE);
//        data.addProperty("expire_seconds", expireSeconds);
//        JsonObject scene = new JsonObject();
//        scene.addProperty("scene_str", sceneStr);
//        JsonObject actionInfo = new JsonObject();
//        actionInfo.add("scene", scene);
//        data.add("action_info", actionInfo);
//        String result = HttpUtil.doPost(WechatQRCodeConfig.getCreateTicketUrl(), params, data.toString());
//        WechatQRCode qrcode = JsonUtil.fromJson(result, WechatQRCode.class);
//        return qrcode == null ? null : qrcode.getTicket();
//    }
//
//    /**
//     * 创建永久二维码(数字)
//     *
//     * @param accessToken
//     * @param sceneId     场景Id
//     * @return
//     */
//    @Override
//    public String createForeverTicket(String accessToken, int sceneId) {
//        TreeMap<String, String> params = new TreeMap<>();
//        params.put("access_token", accessToken);
//        // output data
//        JsonObject data = new JsonObject();
//        data.addProperty("action_name", QRCodeConstant.QR_LIMIT_SCENE);
//        JsonObject scene = new JsonObject();
//        scene.addProperty("scene_id", sceneId);
//        JsonObject actionInfo = new JsonObject();
//        actionInfo.add("scene", scene);
//        data.add("action_info", actionInfo);
//        String result = HttpUtil.doPost(WechatQRCodeConfig.getCreateTicketUrl(), params, data.toString());
//        WechatQRCode qrcode = JsonUtil.fromJson(result, WechatQRCode.class);
//        return qrcode == null ? null : qrcode.getTicket();
//    }
//
//    /**
//     * 创建永久二维码(字符串)
//     *
//     * @param accessToken
//     * @param sceneStr    场景str
//     * @return
//     */
//    @Override
//    public String createForeverTicket(String accessToken, String sceneStr) {
//        TreeMap<String, String> params = new TreeMap<>();
//        params.put("access_token", accessToken);
//        // output data
//        JsonObject data = new JsonObject();
//        data.addProperty("action_name", "QR_LIMIT_STR_SCENE");
//        JsonObject actionInfo = new JsonObject();
//        JsonObject scene = new JsonObject();
//        scene.addProperty("scene_str", sceneStr);
//        actionInfo.add("scene", scene);
//        data.add("action_info", actionInfo);
//        String result = HttpUtil.doPost(WechatQRCodeConfig.getCreateTicketUrl(), params, data.toString());
//        WechatQRCode qrcode = JsonUtil.fromJson(result, WechatQRCode.class);
//        return qrcode == null ? null : qrcode.getTicket();
//    }
//
//
//    /**
//     * 长链接转短链接
//     *
//     * @param accessToken
//     * @param longUrl     长链接
//     * @return
//     */
//    private String toShortQRCodeurl(String accessToken, String longUrl) {
//        TreeMap<String, String> params = new TreeMap<>();
//        params.put("access_token", accessToken);
//        JsonObject data = new JsonObject();
//        data.addProperty("action", QRCodeConstant.LONG_TO_SHORT);
//        data.addProperty("long_url", longUrl);
//        String result = HttpUtil.doPost(WechatQRCodeConfig.getShortQrcodeUrl(),
//                params, data.toString());
//        WechatQRCodeShortUrl wechatQRCodeShortUrl = JsonUtil.fromJson(result, WechatQRCodeShortUrl.class);
//        return wechatQRCodeShortUrl == null ? null : wechatQRCodeShortUrl.getShortUrl();
//    }



}
